package cn.rjzjh.tapestry.tams.pages;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.annotations.ActivationRequestParameter;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.AssetSource;
import org.apache.tapestry5.util.TextStreamResponse;
import org.hibernate.Session;
import org.springframework.security.core.context.SecurityContextHolder;

import cn.rjzjh.commons.util.assistbean.EasyUINode;
import cn.rjzjh.commons.util.web.EasyUiAssist;
import cn.rjzjh.tapestry.busi.bean.EcAuth;
import cn.rjzjh.tapestry.busi.model.ca.CaResource;
import cn.rjzjh.tapestry.busi.model.ca.CaStaff;
import cn.rjzjh.tapestry.busi.service.IMenuService;
import cn.rjzjh.tapestry.busi.service.IStaffService;
import cn.rjzjh.tapestry.busi.service.security.UserInfo;
import cn.rjzjh.tapestry.busi.service.test.IMethodAop;
import cn.rjzjh.tapestry.component.tools.TapestryAssist;
import cn.rjzjh.tapestry.hibernate.services.IHbService;
import cn.rjzjh.tapestry.tams.base.ParentPage;

@Import(stack = "easyuistack", stylesheet = { "${path.easyui}/themes/default/tree.css" })
public class Main extends ParentPage {

	@Inject
	private AssetSource assetSource;
	@Inject
	private IMethodAop methodAop;
	@Inject
	private Session session;
	@Inject
	private IHbService hbService;
	@Inject
	private IStaffService staffService;

	@Inject
	private IMenuService menuService;

	@Property
	private List<CaResource> moduleList;
	@Property
	private CaResource module;

	@Property
	@ActivationRequestParameter
	private Integer moduleId;

	public String getAdminInfo() {
		return methodAop.adminMessage();
	}

	public String getUserInfo() {
		return methodAop.userMessage();
	}

	@Property
	@SessionState
	private EcAuth ecauth;
	private boolean ecauthExists;

	public Asset getModuleImageB() {
		return assetSource.getContextAsset("/resource/images/tool_ico/"
				+ module.getResCode() + "_b.png",
				supportedLocales.getCurLocale());
	}

	public Asset getModuleImageW() {
		return assetSource.getContextAsset("/resource/images/tool_ico/"
				+ module.getResCode() + "_w.png",
				supportedLocales.getCurLocale());
	}

	public String getModuleTitle() {
		return I18NConvert.getStr(module.getResCode());
	}

	/**
	 * 切换菜单
	 *
	 * @return
	 */
	public TextStreamResponse onSwitchMenu() {
		List<EasyUINode> root = menuService.findModuleMenuForRoles(moduleId,
				ecauth.hasRoles(), I18NConvert);
		String json = EasyUiAssist.getTreeFromList(root);
		return new TextStreamResponse("text/html", json);
	}

	String onActivate() {
		Object usobj = SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		if ("anonymousUser".equals(String.valueOf(usobj))) {
			return "index";
		}
		// 判断是否要添加Session
		if (!ecauthExists) {
			UserInfo ud = (UserInfo) usobj;
			ecauth = new EcAuth(ud);// 设置session
		}
		moduleList = menuService.findAllModule(ecauth.hasRoles(), true);
		return null;
	}

	/***
	 * 保存用户
	 *
	 * @return
	 * @throws Exception
	 */
	@CommitAfter
	public TextStreamResponse onSaveUser() throws Exception {
		CaStaff castaff = TapestryAssist
				.getBeanFromPage(CaStaff.class, request);
		int id = castaff.getId();
		CaStaff saveobj = (CaStaff) session.get(CaStaff.class, id);
		saveobj.setEmail(castaff.getEmail());
		saveobj.setGender(castaff.getGender());
		saveobj.setMobile(castaff.getMobile());
		saveobj.setPhone(castaff.getPhone());
		saveobj.setRemark(castaff.getRemark());
		saveobj.setUserName(castaff.getUserName());
		session.update(saveobj);

		ecauth.getUserInfo().getStaff().setUserName(castaff.getUserName());
		ecauth.getUserInfo().getStaff().setEmail(castaff.getEmail());
		ecauth.getUserInfo().getStaff().setGender(castaff.getGender());
		ecauth.getUserInfo().getStaff().setMobile(castaff.getMobile());
		ecauth.getUserInfo().getStaff().setPhone(castaff.getPhone());
		ecauth.getUserInfo().getStaff().setRemark(castaff.getRemark());
		return retSuccInfo();
	}

	/**
	 * 重设密码
	 *
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws NumberFormatException
	 */
	@CommitAfter
	public TextStreamResponse onResetPassword() throws NumberFormatException,
			UnsupportedEncodingException {
		JSONObject parma = TapestryAssist.packParams(request);
		String id = TapestryAssist.getParam(parma, "id");
		String oldPassword = TapestryAssist.getParam(parma, "oldPassword");
		String password = TapestryAssist.getParam(parma, "password");
		String cfmpwd = TapestryAssist.getParam(parma, "cfmpwd");
		if (StringUtils.isEmpty(id) || StringUtils.isEmpty(oldPassword)
				|| StringUtils.isEmpty(password) || StringUtils.isEmpty(cfmpwd)) {
			return retErrorInfo("common.hint.needparam");
		}
		if (!ecauth.getStaff().getPassword()
				.equals(DigestUtils.md5Hex(oldPassword))) {
			return retErrorInfo("tip.main.oldpwd.error");
		}
		if (!password.equals(cfmpwd)) {
			return retErrorInfo("tip.main.pwd.notmatched");
		}
		String newpwd = DigestUtils.md5Hex(password);
		hbService.getQuery("update CaStaff set password=? where id=?")
				.setParameter(0, newpwd).setParameter(1, Integer.parseInt(id))
				.executeUpdate();
		ecauth.getStaff().setPassword(newpwd);
		return retSuccInfo();
	}

	TextStreamResponse onLock() {
		ecauth.setLocked(true);
		return retSuccInfo();
	}

	TextStreamResponse onUnLock() {
		String lockPassword = request.getParameter("lockPassword");
		if (StringUtils.isBlank(lockPassword)) {
			return retErrorInfo("common.hint.needparam");
		}
		if (!DigestUtils.md5Hex(lockPassword).equals(
				ecauth.getStaff().getPassword())) {
			return retErrorInfo("tip.main.user.notcurr");
		}
		ecauth.setLocked(false);
		return retSuccInfo();
	}

	TextStreamResponse onLogout() {
		ecauth = null;
		// TODO 注册Spring中的Token
		return retSuccInfo();
	}
}
